﻿using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Xml;
using Google.ProtocolBuffers.Collections;

namespace WcfService1
{
    public static class SerializerExtension
    {
        public static void WriteObject<T>(this T obj, string path)
        {
            DataContractSerializer s = new DataContractSerializer(typeof(T));
            using (FileStream fs = File.Open(path + typeof(T).Name + ".xml", FileMode.Create))
            {
                //XmlDictionaryWriter binaryWriter = XmlDictionaryWriter.CreateBinaryWriter(fs);
                //s.WriteObject(binaryWriter,obj);
                s.WriteObject(fs, obj);
            }
        }

        public static T ReadObject<T>(this T obj, string path)
        {
            DataContractSerializer s = new DataContractSerializer(typeof(T));
            using (FileStream fs = File.Open(path, FileMode.Open))
            {
                //XmlDictionaryReader binaryReader = XmlDictionaryReader.CreateBinaryReader(fs,
                //                                                                          XmlDictionaryReaderQuotas.Max);

                //obj = (T)s.ReadObject(binaryReader);
                obj = (T)s.ReadObject(fs);
            }
            return obj;
        }

        public static void WriteObject<T>(this T obj, string path,out FileStream stream)
        {
            DataContractSerializer s = new DataContractSerializer(typeof(T));
            using (FileStream fs = File.Open(path + typeof(T).Name + ".xml", FileMode.Create))
            {
                //XmlDictionaryWriter binaryWriter = XmlDictionaryWriter.CreateBinaryWriter(fs);
                //s.WriteObject(binaryWriter,obj);
                stream = fs;
                s.WriteObject(fs, obj);
            }
        }

    }
}